<?php
/**
 * Plugin Shortcode.
 *
 * @package WP cr mobile
 */
class CRMobile_Shortcode
{
    public function __construct()
    {
        add_shortcode('crmobile -review', array(&$this,'shortcode'));
    }

    public function shortcode($atts)
    {
        extract(
            shortcode_atts(
                array(
                    'id'    => '',
                    'exclude' => '',
                    'limit' => 100
                ),
                $atts
            )
        );

        $company = $this->getCompanyById($id);
        if ($company == null) {
            return;
        }
        $reviews = self::getReviews($company->ID, 'review_date', $limit);
        $microdata = self::getMicrodata($company->ID);

        $data = array(
            'name'      => $company->name,
            'microdata' => $microdata,
            'reviews'   => $reviews,
            'exclude'   => $exclude,
            'star'      => plugins_url(
                "assets/stars/{$company->star}",
                CRMobile::FILE
            ),
        );
        return CRMobile_View::render(
            plugin_dir_path(__FILE__).'../../views/shortcode.php',
            $data
        );
    }

    public static function getCompanyByName($name)
    {
        global $wpdb;
        $company_table = $wpdb->prefix . "cr_mobile_companies";
        $query = "SELECT * FROM $company_table WHERE LOWER(name)=LOWER({$name})";
        $company = $wpdb->get_row($query, OBJECT);

        return $company;
    }

    public static function getCompanyById($id)
    {
        global $wpdb;
        $company_table = $wpdb->prefix . "cr_mobile_companies";
        $query = "SELECT * FROM $company_table WHERE id={$id}";
        $company = $wpdb->get_row($query, OBJECT);

        return $company;
    }


    public static function getReviews($id, $sort = 'review_date', $limit = 100)
    {
        global $wpdb;
        $reviews_table = $wpdb->prefix . "cr_mobile_reviews";

        // Get all published reviews
        $query = "SELECT * FROM $reviews_table 
                  WHERE company_id = $id AND status = 'published'
                  ORDER BY {$sort} DESC
                  LIMIT {$limit}";
        $reviews = $wpdb->get_results($query, ARRAY_A);

        return $reviews;
    }

    public static function getMicrodata($id)
    {
        global $wpdb;
        $reviews_table = $wpdb->prefix . "cr_mobile_reviews";

        // Get all published reviews
        $query = "SELECT * FROM $reviews_table 
                  WHERE company_id = $id AND status = 'published'";
        $reviews = $wpdb->get_results($query, ARRAY_A);

        $ratings = 0;
        $count = count($reviews);
        foreach ($reviews as $review) {
            $ratings += $review['rating'];
        }

        $microdata['total'] = $count;
        $microdata['average'] = ($count == 0) ? 0 : $ratings/$count;

        return $microdata;
    }
}
